<template>
  <div style="padding-bottom: 30rpx">
    <view class="end" v-if="!commit_flag">
      <text class="title">售后状态:</text>
      <text class="use_already_apply">
        <u-steps mode="number" :list="numList" :current="step_index"></u-steps>
      </text>
    </view>
    <view class="order">
      <u-card
        class=""
        :title="cardTitle"
        :title-color="`#fff`"
        :head-style="cardHeadClass[1]"
        :body-style="cardBodyClass"
      >
        <view class="card-body" slot="body">
          <view class="line_title">
            <view class="left"> 本次消费商品 </view>
            <view class="right">
              <!-- todo -->
            </view>
          </view>
          <view
            class="u-body-item u-flex u-border-bottom product_item"
            v-for="(product, index) in order.orderItemList"
            :key="'product-' + index"
          >
            <view class="left">
              <view class="img">
                <img :src="OrderItemImg(product.productId)" alt="" />
              </view>
              <view class="content">
                <view class="naem">
                  {{ product.productName }}
                </view>
                <view class="props">
                  {{ product.saleAttrValueArray }}
                </view>
                <view class="number"> x {{ product.num }} </view>
              </view>
            </view>
            <view class="right">
              <view class="price"> ￥ {{ product.realAmount }} </view>
            </view>
          </view>

          <!-- 订单状态 -->
          <view class="line_title">
            <view class="left"> 订单状态 </view>
            <view class="right"> </view>
          </view>
          <view
            class="u-body-item u-flex u-border-bottom order_info_item"
            v-for="os in orderStatus"
            :key="os.id"
          >
            <view class="left">
              {{ os.key }}
            </view>
            <view class="right" :class="{ place_holder: os.key == '订单备注' }">
              {{ os.val }}
            </view>
          </view>
          <!-- end -->

          <!-- 收货信息 -->
          <view class="line_title">
            <view class="left"> 收货人 </view>
            <view class="right"> </view>
          </view>
          <view
            class="u-body-item u-flex u-border-bottom"
            v-for="ri in receiverInfo"
            :key="ri.id"
          >
            <view class="left"> {{ ri.key }}</view>
            <view class="right">
              {{ ri.val }}
            </view>
          </view>
          <!-- end -->
          <view class="line"> </view>
          <view class="line_title">
            <view class="left">申请售后</view>
            <view class="right"> </view>
          </view>
          <view class="u-body-item u-flex u-border-bottom commit_box">
            <view class="no_commit">
              <view class="comdatatext">
                <textarea
                  name="commit"
                  id=""
                  cols="10"
                  rows="5"
                  class="commitTextarea"
                  :class="{ commitText: !commit_flag }"
                  :disabled="disabled"
                  maxlength="100"
                  @input="commitData"
                  :value="comData"
                  placeholder="请填写原因."
                >
                <!-- 123 -->
                </textarea>
                <view class="tipsbox">
                  <text
                    v-show="commit_flag"
                    class="commitTips"
                    :class="{ moreThen100: comData && comData.length == 100 }"
                    >{{ resonLengthTips }}</text
                  >
                </view>
              </view>

              <!-- rate end -->

              <!-- 图片上传 -->
              <view class="imguploadbox">
                <!-- <text>上传图片：</text> -->
                <ck-upload-img
                  v-show="commit_flag"
                  class="bg-img"
                  :selectNum="3"
                  @returnImgUrl="getImgUrl"
                  :initImgList="urls"
                  :token="qnToken"
                ></ck-upload-img>
              </view>
              <!-- end -->

              <!-- 显示 评论的图片 -->
              <view
                v-show="disabled && urls[0].length != 0"
                class="comment_urls_box"
              >
                <img
                  class="comment_urls_item"
                  v-for="(url, index) in urlsByComment"
                  :key="'url-comment-' + index"
                  :src="url"
                />
              </view>
              <!-- 显示 评论的图片  end -->

              <button class="btn_sub" v-if="commit_flag" @tap="showModal()">
                提交申请
              </button>
            </view>
            <!-- <view class="has_commit" v-if="commit_flag"> 
              等待商家退款确认。
            </view> -->
          </view>
        </view>
      </u-card>
    </view>

    <u-toast ref="tips"></u-toast>
    <u-modal
      v-model="modalShow"
      :mask-close-able="true"
      :content="modalContent"
      @confirm="confirm"
      @cancel="cencel"
      show-cancel-button
    ></u-modal>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from "vuex";
import ckUploadImg from "@/components/ck-uploadImg/ck-uploadImg.vue";
// import UToast from "../../../dist/dev/app-plus/static/style/uview-ui/components/u-toast/u-toast.vue";
export default {
  name: "",
  data() {
    return {
      cardTitle: "我的订单",
      qiniuImageURLPrefix: "http://cdn.350800.xyz/",
      cardHeadClass: [
        {
          background: "rgb(92, 131, 75)",
          color: "#fff",
        },
        {
          // visibility:
          display: "none",
        },
      ],
      cardBodyClass: {
        padding: 0,
      },
      sn: "", // 订单sn
      comData: "", // 订单评价
      order: "",
      orderStatus: [],
      receiverInfo: [],
      count: 5, // rate used
      rateVal: 5, // rate used
      commit_flag: true,
      disabled: false, // 有评论就禁止 textarea 点击

      urls: [], // res.urls
      // ck-uploadimg used
      qnToken: "", // 七牛云文件上传token
      imgList: [], //图片上传
      imgUrls: "", // 用来上传给服务器 是公网地址

      // toashShow:false,

      modalContent: "",
      modalShow: false,

      numList: [
        { name: "等待确认" },
        { name: "正在退款" },
        { name: "退款成功" },
      ],
      step_index: 0,
    };
  },
  components: {
    ckUploadImg,
  },
  watch: {},
  computed: {
    ...mapGetters(["getProduct"]),
    OrderItemImg() {
      return (id) => {
        return this.getProduct(id).defaultImg;
      };
    },
    cardStatus() {
      return (order) => {
        if (order.orderStatus == 1) {
          // 订单退款状态 0 || 1
          return "已退款";
        } else {
          if (order.confirmStatus == 1) {
            // 订单确认状态  （用户） 0 || 1
            return "已确认收货";
          } else {
            // 订单状态
            return order.orderStatusChinese;
          }
        }

        // return /
      };
    },
    // 评论文字
    resonLengthTips() {
      return this.comData ? "(" + this.comData.length + " / 100)" : "(0 / 100)";
    },
    // 评论图片
    urlsByComment() {
      let _urls = [];
      if (this.urls.length) {
        if (this.urls[0])
          _urls = this.urls[0].split(";").filter((url) => {
            return url.length != 0;
          });
      }
      return _urls;
    },
  },
  onPullDownRefresh() {
    this.init();
    uni.stopPullDownRefresh();
  },
  onLoad(option) {
    this.sn = option.sn;
    let that = this;
    that.init();
  },

  methods: {
    ...mapMutations(["SET_GOODS"]),
    async init() {
      let that = this;
      // 手动初始化
      console.log("手动初始化");
      // 商品  为了图片
      if (!that.$store.state.goods.length) {
        let _goods = await that.$u.api.getALLgoods();
        that.$store.state.goods = [];
        _goods.list.forEach((ele) => {
          that.SET_GOODS(ele);
        });
      }

      let params = {
        sn: this.sn,
      };
      // 获取order
      that.order = await that.$u.api.getOrderDetail({
        sn: that.sn,
      });
      that.qnToken = await that.$u.api.getCDNToken();

      // 设置orderStatus
      that.setOrderStatus();
      that.setReceiverInfo();

      // 查看 售后详情
      this.$u.api
        .getAfterSale({
          sn: that.sn,
        })
        .then((res) => {
          console.log(res);
          console.log(!res.data);
          if (!res.data && res.reason) {
            that.commit_flag = false;
            that.comData = res.reason;
            that.step_index = res.status;
          } else {
          }
        });
      // 获取订单评价
      //   this.$u.api.getCom(params).then((res) => {
      //     const { content, imgUrls } = res;
      //     // console.log(res.data);
      //     console.log(res);
      //     that.comData = content;
      //     if (content) {
      //       // 用一个flag 来确定是否可以评论
      //       that.commit_flag = false;
      //     }
      //     that.urls = [imgUrls];
      //     if (that.comData) {
      //       that.disabled = true; // :disable="disable" 绑定了
      //     }
      //   });
    },

    commitData(e) {
      this.comData = e.target.value;
    },

    setOrderStatus() {
      let that = this;
      let order = that.order;
      if (that.orderStatus.length) {
        return;
      }
      // that.$set(that.orderStatus[0], "val", that.order.createTime);
      // that.$set(that.orderStatus[1],"val",that.order.createTime)

      that.orderStatus.push({
        id: "os_1",
        key: "下单时间",
        val: order.createTime,
      });
      that.orderStatus.push({
        id: "os_2",
        key: "状态",
        // val: order.orderStatusChinese,
        // 计算属性
        val: that.cardStatus(that.order),
      });
      that.orderStatus.push({
        id: "os_3",
        key: "总价",
        val: "￥ " + order.realAmount + "元",
      });
      that.orderStatus.push({
        id: "os_4",
        key: "订单备注",
        val: order.remark,
      });
    },

    setReceiverInfo() {
      let receiverInfo = this.receiverInfo;
      let order = this.order;
      let that = this;
      if (receiverInfo.length) {
        return;
      }
      receiverInfo.push({
        id: "ri_1",
        key: "收货人",
        val: order.receiverName,
      });
      receiverInfo.push({
        id: "ri_2",
        key: "联系电话",
        val:
          order.receiverPhone.substr(0, 3) +
          "****" +
          order.receiverPhone.substr(7, 4),
      });
      receiverInfo.push({
        id: "ri_3",
        key: "收货地址",
        val: order.receiverDetailAddress,
      });
    },

    showModal() {
      this.modalContent = "确认提交售后申请";
      this.modalShow = true;
    },
    confirm() {
      this.handerSubCommit();
    },
    cencel() {},

    // 提交 售后申请
    handerSubCommit() {
      let that = this;
      const content = that.comData || "该用户没有填写评价.";
      const rateVal = that.rateVal;
      const params = {
        reason: content,
        imgUrls: that.imgUrls,
        orderSn: that.sn,
      };
      console.log(params);
      //   this.$u.api.addCom(params);

      this.$u.api.applyAfterSale(params).then((res) => {
        console.log(res);
        // 商家要送达之后才可以申请售后
        if (res.code == 500) {
          that.$refs.tips.show({
            title:`${res.msg}`,
            type:'warning'
          })
        } else {
          that.$refs.tips.show({
            title: "成功申请售后服务,请等待商家处理.",
            type: "success",
            url: "/pages/orders/orders",
          });
        }
      });
    },

    getImgUrl(resultUrls) {
      var globalThis = this;
      // 拼接上七牛云 bukect 网址前缀
      for (let i = 0; i < resultUrls.length; i++) {
        let urlSuffix = resultUrls[i];
        // 如果已经拼接过 前缀，就跳过
        if (urlSuffix && urlSuffix.startsWith(globalThis.qiniuImageURLPrefix)) {
          continue;
        }

        resultUrls[i] = globalThis.qiniuImageURLPrefix + "/" + urlSuffix;
      }
      console.log("图片url处理完毕");
      console.log(resultUrls);
      // globalThis.goodInfo.ImageUrls = resultUrls.join(";");
      globalThis.imgUrls = resultUrls.join(";");
    },

    ChooseImage() {
      uni.chooseImage({
        count: 5, //默认9
        sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ["album"], //从相册选择
        success: (res) => {
          if (this.imgList.length != 0) {
            this.imgList.concat(res.tempFilePaths);
          } else {
            this.imgList = res.tempFilePaths;
          }
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/pages/pay/pay.scss";
@import "~@/pages/orders/order-detail.scss";

.end {
  display: inline;
  padding: 20rpx 40rpx;
  .title {
    color: $uni-text-color;
    margin-bottom: 30rpx;
    display: inline-block;
  }
}
</style>
